package com.powernode.money.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.powernode.money.constant.Constants;
import com.powernode.money.model.BidInfo;
import com.powernode.money.model.FinanceAccount;
import com.powernode.money.model.LoanInfo;
import com.powernode.money.model.User;
import com.powernode.money.service.*;
import com.powernode.money.vo.ApiResult;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.Date;

@Controller
public class LoanInfoController {
    @Reference(interfaceClass = LoanInfoService.class, version = "1.0.0")
    private LoanInfoService loanInfoService;
    @Reference(interfaceClass = BidInfoService.class, version = "1.0.0")
    private BidInfoService bidInfoService;
    @Reference(interfaceClass = RechargeRecordService.class, version = "1.0.0")
    private RechargeRecordService rechargeRecordService;
    @Reference(interfaceClass = FinanceAccountService.class, version = "1.0.0")
    private FinanceAccountService financeAccountService;
    @GetMapping("/loan/loan")
    public String loan(int ptype, Integer pageNum, Model model) {
        int pageSize=6;
        pageNum =pageNum ==null?1:pageNum;
        int rows =loanInfoService.queryRowsByPtype(ptype);
        int rowsSize=rows%pageSize ==0? rows/pageSize:rows/pageSize+1;
        model.addAttribute("loanInfoList", loanInfoService.queryByProductTypeWithPage(ptype, pageNum, pageSize));
        model.addAttribute("pageNum",pageNum);
        model.addAttribute("rows",rows);
        model.addAttribute("rowsSize",rowsSize);
        model.addAttribute(Constants.INVEST_TOP,bidInfoService.queryTopRankFromRedis(5));
        return "loan";
    }

    @GetMapping("/loan/loanInfo")
    public String loanInfo(int id, Model model, HttpSession session){
        //推送产品信息
        model.addAttribute("loanInfo", loanInfoService.queryByPrimaryKey(id));
        model.addAttribute("loanTop", bidInfoService.queryByLoanId(String.valueOf(id)));
        //如果用户是已登录，推送账号余额
        User user = (User)session.getAttribute(Constants.SESSION_USER);
        if(user!=null){
            model.addAttribute("financeAccount", financeAccountService.queryByUid(user.getId()));
        }

        return "loanInfo";
    }




    @GetMapping("/loan/ShouYi")
    @ResponseBody
    public ApiResult shouYi(int id,  Double bidMoney,HttpSession session){
        //推送产品信息

        LoanInfo loanInfo=loanInfoService.queryByPrimaryKey(id);
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        if (user!=null){
            if (loanInfo != null) {
                DecimalFormat df = new DecimalFormat("#.00");
                return ApiResult.success(df.format((bidMoney * (loanInfo.getRate() / 100 / 365) * loanInfo.getCycle() * 30)));
            }
        }else {
            return ApiResult.error("请先登录");
        }

        return ApiResult.error("投资失败");


    }




    @PostMapping("/loan/investNow")
    @ResponseBody
    public ApiResult investNow(int id,  Double bidMoney,HttpSession session){

        LoanInfo loanInfo=loanInfoService.queryByPrimaryKey(id);
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        if (user!=null){
            FinanceAccount financeAccount= financeAccountService.queryByUid(user.getId());
            if (loanInfo != null && bidMoney<financeAccount.getAvailableMoney()) {
                if (loanInfo.getLeftProductMoney()-bidMoney>=0){
                   financeAccount.setAvailableMoney(financeAccount.getAvailableMoney()-bidMoney);
                   int count =financeAccountService.executeUpdateByPrimaryKeySelective(financeAccount);
                   loanInfo.setLeftProductMoney(loanInfo.getLeftProductMoney()-bidMoney);
                   int countLoan=loanInfoService.executeUpdateByPrimaryKeySelective(loanInfo);
                   if (count >0 &&countLoan>0){
                       bidInfoService.executeInsertSelective(NewBidInfo(user.getId(),id,bidMoney,1));
                       return ApiResult.success();
                   }
               }else {
                   if (bidMoney-loanInfo.getLeftProductMoney()>0){
                       double d=bidMoney-loanInfo.getLeftProductMoney();
                       financeAccount.setAvailableMoney(financeAccount.getAvailableMoney()-loanInfo.getLeftProductMoney());
                       int count =financeAccountService.executeUpdateByPrimaryKeySelective(financeAccount);
                       loanInfo.setLeftProductMoney(0.0);
                       int countLoan=loanInfoService.executeUpdateByPrimaryKeySelective(loanInfo);
                       if (count >0 &&countLoan>0){
                           bidInfoService.executeInsertSelective(NewBidInfo(user.getId(),id,d,1));
                           return ApiResult.success("投资额度已满，返"+d+"元");
                       }
                   }
               }

            }
        }else {
            return ApiResult.error("请先登录");
        }

        return ApiResult.error("投资失败");


    }

    private static BidInfo NewBidInfo(Integer uid,Integer loanId,Double bidMoney,Integer bidStatus){
        BidInfo bidInfo =new BidInfo();
        bidInfo.setBidTime(new Date());
        bidInfo.setUid(uid);
        bidInfo.setLoanId(loanId);
        bidInfo.setBidMoney(bidMoney);
        bidInfo.setBidStatus(bidStatus);
        return bidInfo;
    }
}
